package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 12/25/20 9:56 AM
 *
 * https://leetcode-cn.com/problems/linked-list-cycle-lcci/
 */
public class _面试题_02_08_环路检测 {

    public ListNode detectCycle(ListNode head) {

        if (head == null || head.next == null) {

            return null;
        }

        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {

            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {

                break;
            }
        }

        // 不存在环
        if (fast == null || fast.next == null) {

            return null;
        }

        fast = head;

        while (fast != slow) {

            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
